package com.hrm.service.impl;

import cn.hutool.core.date.DateUtil;
import com.hrm.dao.EmployeeMapper;
import com.hrm.dao.SysEventMapper;
import com.hrm.dto.EmpDepDTO;
import com.hrm.dto.StaffPercentBySex;
import com.hrm.dto.StarffPercentByDepartment;
import com.hrm.entity.Employee;
import com.hrm.entity.SysEvent;
import com.hrm.utils.SysEventDescription;
import com.hrm.service.EmployeeService;
import com.hrm.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Auther:
 * @Date: 2020/5/20 09:59
 * @Description:
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    SysEventMapper sysEventMapper;


    @Override
    public boolean checkName(Employee employee) {
        if(employeeMapper.selectByName(employee.getLoginName()) != null){
            return false;
        }else return true;
    }

    @Override
    public boolean checkPhone(Employee employee) {
        if(employeeMapper.selectByPhone(employee.getPhone()) != null){
            return false;
        }else return true;
    }

    @Override
    public boolean checkEmail(Employee employee) {
        if(employeeMapper.selectByEmail(employee.getEmail()) != null){
            return false;
        }else return true;
    }

    @Override
    public Employee loginCheck(Employee employee) {
        Employee employeeSession = employeeMapper.selectByName(employee.getLoginName());
        if (MySecurity.encryptUserPassword(employee.getPassword(),"5").equals(employeeSession.getPassword()))
        {
            String description = SysEventDescription.addSysEventDescription(employeeSession.getId(),employeeSession.getName(),"登录系统");
            SysEvent sysEvent = SysEventDescription.addSysEvent(DateUtil.date(),description);
            sysEventMapper.insert(sysEvent);
            return employeeSession ;}
        else return null;
    }

    @Override
    public boolean Registe(Employee employee) {
        employee.setPassword(MySecurity.encryptUserPassword(employee.getPassword(),"5"));
        employee.setGender("保密");
        employee.setIcon("/imgs/icon/user_default_icon.jpg");
        employee.setJobTitle("待分配");
        employee.setDeptId(999);
        employee.setBasicSalary(0);
        employee.setVacation(10);
        employeeMapper.insert(employee);
        String description = SysEventDescription.addSysEventDescription(employee.getId(),employee.getName(),"注册用户");
        SysEvent sysEvent = SysEventDescription.addSysEvent(DateUtil.date(),description);
        sysEventMapper.insert(sysEvent);
        return true;
    }

    @Override
    public EmailVerifyCode sendCodeToEmail(String email) {
        String emailaddress = email;
        String code = VerifyCode.randomCode();
        String msg = "收到来自人力资源管理系统的验证码:\n" + code + "\n 有效时间:" + EmailVerifyCode.validTime/(1000 * 60) + "分钟";
        try {
            MailUtil.SendMail(emailaddress,msg);
            return new EmailVerifyCode(email,code, MyTimeUtil.getTime());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean emailCodeTest(String code, HttpSession session) {
        EmailVerifyCode emailVerifyCode = (EmailVerifyCode) session.getAttribute("emailVerifyCode");
        if(code == null || !code.equals(emailVerifyCode.getCode()) || !emailVerifyCode.isValid()){
            return false;
        }else return true;
    }

    @Override
    public boolean resetPwd(Employee employee) {
        Employee employeeSession = employeeMapper.selectByEmail(employee.getEmail());
        employeeSession.setPassword(MySecurity.encryptUserPassword(employee.getPassword(),"5"));
        String description = SysEventDescription.addSysEventDescription(employeeSession.getId(),employeeSession.getName(),"重置密码");
        SysEvent sysEvent = SysEventDescription.addSysEvent(DateUtil.date(),description);
        sysEventMapper.insert(sysEvent);
        employeeMapper.updateEmployee(employeeSession);
        return true;

    }

    @Override
    public String uploadIcon(MultipartFile file, HttpServletRequest request, Integer id) {
        {
            String prefix = "";

            String uploadDir ="/imgs/icon";
            String absoluFilePath = "";
            String relaFilePath = "";

            DateFormat format1 = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");
            String dateStr = format1.format(new Date());

            //保存上传
            OutputStream out = null;
            InputStream fileInput = null;
            try {
                if (file != null) {
                    String originalName = file.getOriginalFilename();
                    prefix = originalName.substring(originalName.lastIndexOf(".") + 1);
                    String filepath = request.getServletContext().getRealPath(uploadDir); //文件存放文件夹路径名
                    filepath = filepath.replace("\\", "/");
                    String fileName = id + "_icon_" + dateStr + "." + prefix; //文件名
                    absoluFilePath = filepath + "/" + fileName;//绝对路径
                    relaFilePath = uploadDir + "/" + fileName;
                    System.out.println(relaFilePath);
                    File files = new File(absoluFilePath);
                    //打印查看上传路径
                    System.out.println(filepath);
                    if (!files.getParentFile().exists()) {
                        files.getParentFile().mkdirs();
                    }
                    file.transferTo(files);
                }
            } catch (Exception e) {
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                    if (fileInput != null) {
                        fileInput.close();
                    }
                } catch (IOException e) {
                }
            }

            return relaFilePath;
        }
    }

    @Override
    public boolean setInfo(Employee employee) {
        Employee realEmployee = employeeMapper.selectByPrimaryKey(employee.getId());
            if(!(realEmployee.getJobTitle().equals(employee.getJobTitle()))) return false;
            else {
                employeeMapper.updateEmployee(employee);
                String description = SysEventDescription.addSysEventDescription(employee.getId(),employee.getName(),"变更个人信息");
                SysEvent sysEvent = SysEventDescription.addSysEvent(DateUtil.date(),description);
                sysEventMapper.insert(sysEvent);
                return true;
            }
        }

    @Override
    public boolean modifyEmail(Employee employee) {
        employeeMapper.updateEmployee(employee);
        String description = SysEventDescription.addSysEventDescription(employee.getId(),employee.getName(),"更改用户邮箱");
        SysEvent sysEvent = SysEventDescription.addSysEvent(DateUtil.date(),description);
        sysEventMapper.insert(sysEvent);
        return true;
    }

    @Override
    public void updateSession(HttpSession session, Integer id) {
        session.removeAttribute("user");
        Employee employeeSession = employeeMapper.selectByPrimaryKey(id);
        session.setAttribute("user",employeeSession);

    }

    @Override
    public List<EmpDepDTO> empDepList() {
        return employeeMapper.empDepList();
    }

    @Override
    public List<String> jobTitleList() {
        return employeeMapper.jobTitleList();
    }

    @Override
    public List<EmpDepDTO> queryEmpDepByName(Employee employee) {
        return employeeMapper.queryEmpDepByName(employee);
    }

    @Override
    public boolean updateEmp(Employee employee) {
        employeeMapper.updateEmployee(employee);
        return true;
    }

    @Override
    public long countEmp(Integer deptId) {
        return employeeMapper.countEmp(deptId);
    }

    @Override
    public List<EmpDepDTO> queryEmpDepByDepId(Integer deptId) {
        return employeeMapper.queryEmpDepByDepId(deptId);
    }

    @Override
    public List<Employee> unEmployeeList() {
        return employeeMapper.unEmployeeList();
    }

    @Override
    public boolean deleteUnEmp(Integer id) {
        employeeMapper.deleteByPrimaryKey(id);
        return true;
    }

    @Override
    public StaffPercentBySex staffPercent() {
        StaffPercentBySex staffPercentBySex = employeeMapper.staffPercent();
        return staffPercentBySex;
    }

    @Override
    public List<StarffPercentByDepartment> staffPercentByDepartment() {
        List<StarffPercentByDepartment> starffPercentByDepartment = employeeMapper.staffPercentByDepartment();
        return starffPercentByDepartment;
    }


}
